package cn.geminis.crypto.csp;

import cn.geminis.crypto.core.key.PublicKey;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;

import java.io.Closeable;

/**
 * @author puddi
 */
public abstract class AbstractAsymmetricBlockCipher implements AsymmetricBlockCipher, Closeable {

    public abstract byte[] getPublicKey();

    public byte[] encrypt(byte[] data, byte[] publicKey) {
        var pk = new PublicKey(publicKey);
        this.init(true, pk.getKeyParameter());
        try {
            return this.processBlock(data, 0, data.length);
        } catch (InvalidCipherTextException e) {
            throw new RuntimeException("非对称加密失败", e);
        }
    }

    public byte[] decrypt(byte[] data) {
        this.init(false, null);
        try {
            return this.processBlock(data, 0, data.length);
        } catch (InvalidCipherTextException e) {
            throw new RuntimeException("非对称解密失败", e);
        }
    }

}
